package com.smallkingson.ylib.core.utils;

import android.util.Log;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class YFps implements Runnable {
  volatile int frame;
  long end;
  private String name;
  String threadInfo;
  private static ExecutorService mService = Executors.newCachedThreadPool();

  volatile boolean isStart = true;
  private String tag;

  public YFps(String name) {

    this.name = name;

    mService.execute(this);
  }

  @Override public void run() {
    while (isStart) {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      Log.d("Y->", threadInfo
          + " name: "
          + YFps.this.name
          + " tag: "
          + (tag == null ? "" : tag)
          + " fps:"
          + frame);
      frame = 0;
    }
  }

  public void stop() {
    isStart = false;
  }

  public void framePlus(String tag) {
    if (threadInfo == null) {
      Thread thread = Thread.currentThread();
      threadInfo = "Thread:" + thread.getName() + "#" + thread.getId();
      StackTraceElement trace = new Throwable().getStackTrace()[tag == null ? 2 : 1];
      threadInfo = "["
          + android.os.Process.myPid()
          + "$"
          + Thread.currentThread().getName()
          + "]"
          + "("
          + trace.getFileName()
          + ":"
          + trace.getLineNumber()
          + ")"
          + "<"
          + trace.getMethodName()
          + ">";
    }
    this.tag = tag;
    frame++;
  }

  public void framePlus() {
    framePlus(null);
  }
}